import React, { useState, useEffect, memo } from 'react';
import { Button, Popover } from '@maycur/antd5';
import { isEqual, cloneDeep } from 'lodash';
import ColumnSetPanel from './ColumnSetPanel';
import './style/ColumnSet.less';

const prefix = 'mctable';

function ColumnSet(props) {
    const { dataSource, onEnd, name, keepLastItem, onConfigChange } = props;

    const [btnName, setBtnName] = useState();
    const [visible, setVisible] = useState();
    const [panels, setPanels] = useState([...dataSource]);    
    const triggerEnd = () => {
        if (!isEqual(panels, dataSource)) {
            onEnd(panels, true);
        }
    };

    const onVisibleChange = (visible) => {
        setVisible(visible);
        if (!visible) {
            triggerEnd();
        }
    };

    const closePanel = () => {
        setVisible(false);
        triggerEnd();
    };

    const onChange = (newValue) => {
        onConfigChange && onConfigChange(newValue);
        setPanels(newValue);
    };

    useEffect(() => {
        if (name !== btnName && name !== '...') {
            setBtnName(name);
        }
    }, [name, btnName]);

    useEffect(() => {
        setPanels([...dataSource]);
    }, [dataSource]);

    return (
        <Popover
            placement="bottomRight"
            trigger="click"
            visible={visible}
            overlayClassName={`${prefix}-column-set-card`}
            onVisibleChange={onVisibleChange}
            content={
                <ColumnSetPanel
                    dataSource={panels}
                    onChange={onChange}
                    closePanel={closePanel}
                    keepLastItem={keepLastItem}
                />
            }
        >
            <Button
                style={{
                    marginRight: 0,
                    marginLeft: 8,
                    borderRadius: 4,
                    borderColor: '#E1E1E1'
                }}
                type="primary"
                disabled={!Array.isArray(dataSource) || dataSource.length === 0}
                ghost
            >
                {btnName}
            </Button>
        </Popover>
    );
}

export default memo(ColumnSet, (prevProps, nextProps) => {
    return prevProps.dataSource === nextProps.dataSource
        && prevProps.name === nextProps.name;
});
